﻿// -----------------------------------------------------------------------
// <copyright file="ByteConvertor.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace PortableImagingLibrary.Convertors
{
    using System.Diagnostics.Contracts;

    internal static class ByteConvertor
    {
        public static int BytesToInt(byte[] source, int startIndex)
        {
            Contract.Requires(startIndex >= 0);
            Contract.Requires(source != null);
            Contract.Requires(source.Length >= (startIndex + 4));

            return (source[startIndex] << 24)
                + (source[startIndex + 1] << 16)
                + (source[startIndex + 2] << 8)
                + source[startIndex + 3];
        }

        public static int ReplaceByte(int value, int byteIndex, byte newByte)
        {
            return (value & ~(0xFF << (byteIndex * 8))) | (newByte << (byteIndex * 8));
        }

        public static byte GetByte(uint value, byte index)
        {
            const int bitsInUint = sizeof(uint) * 8;
            const int bitsInByte = sizeof(byte) * 8;

            uint subValue = value << (bitsInUint - (index + 1) * bitsInByte);
            var result = (byte)(subValue >> (((bitsInUint / bitsInByte) - 1) * bitsInByte));

            return result;
        }
    }
}
